package edu.tcc.iot.persistence.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import edu.tcc.iot.domain.Shelf;
import edu.tcc.iot.persistence.DBContext;
import edu.tcc.iot.persistence.dao.IShelfDAO;
import edu.tcc.iot.utils.DaoUtils;
import edu.tcc.iot.utils.ServiceLocator;


public class ShelfDAO implements IShelfDAO{

	private DBContext dbContext = ServiceLocator.getInstance(DBContext.class);

	
	@Override
	public Shelf findById(long id) throws SQLException {
		Shelf result = null;
		Connection connection = dbContext.getConnection();
		try {
			String sql = dbContext.getShelfQuery("dao.findby.id");
			PreparedStatement statement = connection.prepareStatement(sql);
			statement.setLong(1, id);
			ResultSet shelf = statement.executeQuery();
			if(shelf.first()){
				result = DaoUtils.shelfFromResultSet(shelf);
			}
		} catch (SQLException e) {
			connection.rollback();
		}
		finally{
			connection.close();
		}
		return result;
	}

	
	@Override
	public synchronized Shelf add(Shelf shelf) throws SQLException {
		Shelf result = null;
		Connection connection = dbContext.getConnection();
		try {
			String sql = dbContext.getShelfQuery("dao.add");
			PreparedStatement statement = connection.prepareStatement(sql);
			statement.setLong(1, shelf.getId());
			result = new Shelf(statement.executeUpdate());

		} catch (SQLException e) {
			connection.rollback();
		}
		finally{
			connection.close();
		}
		return result;
	}

	
	@Override
	public synchronized void remove(long id) throws SQLException {
		Connection connection = dbContext.getConnection();
		try {
			String sql = dbContext.getShelfQuery("dao.remove");
			PreparedStatement statement = connection.prepareStatement(sql);
			statement.setLong(1, id);
			statement.executeUpdate();
		} catch (SQLException e) {
			connection.rollback();
		}
		finally{
			connection.close();
		}
	}

}
